# 处理业务逻辑
import re
from flask_shop.user import user, user_api
from flask_shop import models, db
from flask import request
from flask_restful import Resource, reqparse
from flask_shop.utils.message import to_dict_msg
from flask_shop.utils.tokens import generate_author_token, verify_author_token, login_required


@user.route("/")
def index():
    return "User Hello!"


class User(Resource):
    def get(self):
        try:
            id = int(request.args.get("id").strip())
            usr = models.User.query.filter_by(id=id).first()
            if usr:
                return to_dict_msg(200, usr.to_dict(), "获取用户成功！")
            else:
                return to_dict_msg(200, [], "没有此用户！")
        except Exception as e:
            print(e)
            return to_dict_msg(1000)

    def post(self):
        name = request.form.get("name")
        pwd = request.form.get("pwd")
        real_pwd = request.form.get("real_pwd")
        nick_name = request.form.get("nick_name")
        phone = request.form.get("phone")
        email = request.form.get("email")

        # 验证数据的正确性
        if not all([name, pwd, real_pwd]):
            return to_dict_msg(1000)
        if len(name) < 2:
            return to_dict_msg(1011)
        if len(pwd) < 2:
            return to_dict_msg(1012)
        if pwd != real_pwd:
            return to_dict_msg(1013)
        if not re.match(r"1[345678]\d{9}", phone):
            return to_dict_msg(1014)
        if not re.match(r"^\w+([-+.]\w+)*@\w+([-.]\w+)*\.\w+([-.]\w+)*$", email):
            return to_dict_msg(1015)
        try:
            rid = int(request.form.get('role_name')) if request.form.get('role_name') else 0
            usr = models.User(name=name, password=pwd, nick_name=nick_name, phone=phone, email=email, rid=rid)
            db.session.add(usr)
            db.session.commit()
            return to_dict_msg(200)
        except Exception:
            return to_dict_msg(2000)

    # 修改用户数据

    def put(self):
        try:
            id = int(request.form.get('id').strip())
            email = request.form.get('email').strip() if request.form.get('email') else ''
            phone = request.form.get('phone').strip() if request.form.get('phone') else ''
            rid = int(request.form.get('role_name')) if request.form.get('role_name') else 0

            usr = models.User.query.get(id)
            if usr:
                usr.email = email
                usr.phone = phone
                usr.rid = rid
                db.session.commit()
                return to_dict_msg(200, msg='修改数据成功！')
            else:
                return to_dict_msg(1018)
        except Exception as e:
            print(e)
            return to_dict_msg(1000)

    def delete(self):
        try:
            id = request.args.get('id')
            usr = models.User.query.get(id)
            if usr:
                db.session.delete(usr)
                db.session.commit()
                return to_dict_msg(200, msg="删除成功！")
            else:
                return to_dict_msg(1019)
        except Exception as e:
            print(e)
            return to_dict_msg(2000)


user_api.add_resource(User, "/user")  # 给User类加"/user"视图


class UserList(Resource):
    def get(self):
        parser = reqparse.RequestParser()  # 接收参数并加以验证
        # 给parser增加属性
        parser.add_argument("name", type=str)
        parser.add_argument("pnum", type=int)
        parser.add_argument("psize", type=int)
        try:
            # 属性给与args实例：把parser中设置的所有"add_argument"给返回到args子类实例当中
            # 那么parser中增加的属性内容都会在args实例中，使用即可
            args = parser.parse_args()
            name = args.get("name")
            pnum = args.get("pnum") if args.get("pnum") else 1
            psize = args.get("psize") if args.get("psize") else 10
            if name:
                users_p = models.User.query.filter(models.User.name.like(f"%{name}%")) \
                    .paginate(pnum, psize)  # 按姓名模糊查询    分页要第几页数据，一页要多少数据
            else:
                users_p = models.User.query.paginate(pnum, psize)
            data = {
                "pnum": pnum,
                "totalPage": users_p.total,
                "users": [u.to_dict() for u in users_p.items]
            }
            return to_dict_msg(200, data, "获取用户列表成功！")
        except Exception as e:
            print(e)
            return to_dict_msg(1000)


user_api.add_resource(UserList, '/user_list')  # 创建映射关系


@user.route("/login", methods=["POST"])
def login():
    name = request.form.get("name")
    pwd = request.form.get("pwd")

    if not all([name, pwd]):  # 判断是否全为真值,只要有一个为" ","None","False"
        return {"status": 1000, "message": "数据不完整"}
    if len(name) > 1:
        usr = models.User.query.filter_by(name=name).first()

        if usr:
            if usr.check_password(pwd):
                token = generate_author_token(usr.id, 100000000000)
                verify_author_token(token)
                return to_dict_msg(200, data={"token": token})

    return {"status": 1001, "message": "用户名或密码错误"}


# 重置密码
@user.route('/reset', methods=["GET"])
def reset():
    try:
        id = int(request.args.get('id'))
        usr = models.User.query.get(id)
        usr.password = "123"
        db.session.commit()
        return to_dict_msg(200, msg="重置密码成功")
    except Exception as e:
        print(e)
        return to_dict_msg(2000)


@user.route("/test")  # 避免每次重启“SECRET_KEY”都会变化
@login_required
def test_login_req():
    return to_dict_msg(200)
